<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="showDialog=true"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table v-loading="loading" :data="list">
              <el-table-column type="index" label="序号" width="120" :index="indexMethod" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="assgin(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="showEdit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 4, 5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
              <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="角色名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                  <el-input v-model="form.description" placeholder="请输入角色描述" />
                </el-form-item>
              </el-form>

              <template #footer>
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="submitBtn">确认</el-button>
              </template>
            </el-dialog>

          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible="showAssignDialog" @open="open" @close="closeAssignDialog">
        <el-tree
          ref="tree"
          v-loading="show"
          node-key="id"
          :data="permissionData"
          :props="{label:'name'}"
          show-checkbox
          default-expand-all
          check-strictly
        />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="assginPerm">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { reqGetRoleList, reqDeleteRole, reqAddRole, reqGetRoleDetail, reqUpdateRole, reqAssignPerm } from '@/api/setting'
import { reqGetPermissionList } from '@/api/permission'
import { reqGetCompanyById } from '@/api/company'
import { mapState } from 'vuex'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      list: [],
      page: 1, // 当前页
      pagesize: 5, // 每页条数
      total: 0, // 总条数
      loading: false,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }],
        description: [{ required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }]
      },
      companyForm: [],
      showAssignDialog: false,
      roleId: '',
      permissionData: [],
      show: false
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getRoleList() // 获取角色列表
    this.getCompanyById()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const { data } = await reqGetRoleList(this.page, this.pagesize)
      const { total, rows } = data
      this.total = total
      this.list = rows
      this.loading = false
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getRoleList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    async delRole(id) {
      const res = await this.$confirm('确认要删除该角色吗?', '温馨提示').catch(error => error)
      if (res !== 'confirm') return
      await reqDeleteRole(id)
      if (this.list.length === 1 && this.page > 1) this.page--
      this.getRoleList()
      this.$message.success('删除角色成功')
    },
    closeDialog() {
      this.showDialog = false
      this.form = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    },
    submitBtn() {
      this.$refs.roleForm.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          // 编辑操作
          await reqUpdateRole(this.form)
        } else {
          // 添加操作
          await reqAddRole(this.form)
        }
        this.showDialog = false
        this.getRoleList()
        this.$message.success('操作成功')
      })
    },
    async showEdit(id) {
      const { data } = await reqGetRoleDetail(id)
      this.form = data
      this.showDialog = true
    },
    async getCompanyById() {
      const { data } = await reqGetCompanyById(this.userInfo.id)
      this.companyForm = data
    },
    assgin(id) {
      this.showAssignDialog = true
      this.roleId = id
    },
    closeAssignDialog() {
      this.showAssignDialog = false
      this.$refs.tree.setCheckedKeys([])
    },
    async open() {
      this.show = true
      const { data } = await reqGetPermissionList()
      this.permissionData = tranListToTreeData(data, '0')
      Promise.all([this.getRoleDetail()]).then(() => {
        this.show = false
      })
    },
    async getRoleDetail() {
      const { data: { permIds }} = await reqGetRoleDetail(this.roleId)
      this.$refs.tree.setCheckedKeys(permIds)
    },
    async assginPerm() {
      const a = this.$refs.tree.getCheckedKeys()
      await reqAssignPerm({ id: this.roleId, permIds: a })
      this.$message.success('修改权限成功')
      this.closeAssignDialog()
    }
  }
}
</script>
<style>

</style>
